<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:schedules:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:schedules:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:schedules:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:schedules:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schedulesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="医生ID" align="center" prop="doctorId" width="50px"/> -->
      <el-table-column label="医生姓名" align="center" prop="doctorName" width="50px"/>
      <el-table-column label="科室名称" align="center" prop="deptName" width="50px"/>
      <el-table-column label="排班日期" align="center" prop="date" width="100px" />
      <el-table-column label="上午" align="center" width="300px">
        <template slot-scope="scope">
          <el-card style="background-color: #e6ffe6; border-color: #e6ffe6; height: 100px;">
            <el-tag style="margin-bottom: 10px;">
              <span>开始时间: {{ scope.row.morningStart}}</span>
              <span>~</span>
              <span>结束时间: {{ scope.row.morningEnd}}</span>
            </el-tag>
            <el-tag>
              <span>上午剩余号源: </span>
              <span>{{ scope.row.morningQuota }}</span>
            </el-tag>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column label="下午" align="center" width="300px">
        <template slot-scope="scope">
          <el-card style="background-color: pink; border-color: #e6ffe6; height: 100px; display: flex; justify-content: center; align-items: center;">
            <div v-if="scope.row.nightStart && scope.row.nightEnd">
              <el-tag style="margin-bottom: 10px;">
                <span>开始时间: {{ scope.row.nightStart }}</span>
                <span>~</span>
                <span>结束时间: {{ scope.row.nightEnd }}</span>
              </el-tag>
              <el-tag>
                <span>晚间剩余号源: </span>
                <span>{{ scope.row.nightQuota }}</span>
              </el-tag>
            </div>
            <div  v-else>
              <el-tag>
                <span>暂无安排</span>
              </el-tag>
            </div>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column label="夜间" align="center" width="300px">
        <template slot-scope="scope">
          <el-card style="background-color: DodgerBlue; border-color: #e6ffe6; height: 100px; display: flex; justify-content: center; align-items: center;">
            <div v-if="scope.row.nightStart && scope.row.nightEnd">
              <el-tag style="margin-bottom: 10px;">
                <span>开始时间: {{ scope.row.nightStart }}</span>
                <span>~</span>
                <span>结束时间: {{ scope.row.nightEnd }}</span>
              </el-tag>
              <el-tag>
                <span>晚间剩余号源: </span>
                <span>{{ scope.row.nightQuota }}</span>
              </el-tag>
            </div>
            <div v-else>
              <el-tag>
                <span>暂无安排</span>
              </el-tag>
            </div>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:schedules:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:schedules:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医生排班对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生姓名" prop="doctorName">
          <el-select v-model="form.doctorName" placeholder="请选择医生姓名">
            <el-option
              v-for="doctor in doctorList"
              :key="doctor.value"
              :label="doctor.label"
              :value="doctor.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="科室名称" prop="deptName">
          <el-select v-model="form.deptName" placeholder="请选择科室名称">
            <el-option
              v-for="dept in deptList"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排班日期" prop="date">
          <el-input v-model="form.date" placeholder="请输入排班日期" />
        </el-form-item>
        <el-form-item label="上午开始时间" prop="morningStart">
          <el-date-picker clearable
            v-model="form.morningStart"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="请选择上午开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上午结束时间" prop="morningEnd">
          <el-date-picker clearable
            v-model="form.morningEnd"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="请选择上午结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下午开始时间" prop="afternoonStart">
          <el-date-picker clearable
            v-model="form.afternoonStart"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="请选择下午开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下午结束时间" prop="afternoonEnd">
          <el-date-picker clearable
            v-model="form.afternoonEnd"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="请选择下午结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="夜间开始时间" prop="nightStart">
          <el-date-picker clearable
            v-model="form.nightStart"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="请选择夜间开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="夜间结束时间" prop="nightEnd">
          <el-date-picker clearable
            v-model="form.nightEnd"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="请选择夜间结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上午号源数量" prop="morningQuota">
          <el-input v-model="form.morningQuota" placeholder="请输入上午号源数量" />
        </el-form-item>
        <el-form-item label="下午号源数量" prop="afternoonQuota">
          <el-input v-model="form.afternoonQuota" placeholder="请输入下午号源数量" />
        </el-form-item>
        <el-form-item label="夜间号源数量" prop="nightQuota">
          <el-input v-model="form.nightQuota" placeholder="请输入夜间号源数量" />
        </el-form-item>
        <el-form-item label="上午剩余号源" prop="morningRemaining">
          <el-input v-model="form.morningRemaining" placeholder="请输入上午剩余号源" />
        </el-form-item>
        <el-form-item label="下午剩余号源" prop="afternoonRemaining">
          <el-input v-model="form.afternoonRemaining" placeholder="请输入下午剩余号源" />
        </el-form-item>
        <el-form-item label="夜间剩余号源" prop="nightRemaining">
          <el-input v-model="form.nightRemaining" placeholder="请输入夜间剩余号源" />
        </el-form-item>
        <el-form-item label="删除标志" prop="deleted">
          <el-input v-model="form.deleted" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->
  
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医生姓名" prop="doctorName">
              <el-select v-model="form.doctorId" placeholder="请选择医生姓名" @change="handleDoctorChange">
                <el-option
                  v-for="doctor in doctorList"
                  :key="doctor.value"
                  :label="doctor.label"
                  :value="doctor.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
            <el-col :span="12">
            <el-form-item label="排班日期" prop="date">
              <el-date-picker
                v-model="form.date"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择排班日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          
          <el-col :span="12">
            <el-form-item label="上午开始时间" prop="morningStart">
              <el-time-picker v-model="form.morningStart" placeholder="请输入上午开始时间" 
              format="HH:mm"
              value-format="HH:mm"/>
            </el-form-item>
            
          </el-col>
          <el-col :span="12">
            <el-form-item label="上午结束时间" prop="morningEnd">
              <el-time-picker v-model="form.morningEnd" placeholder="请输入上午结束时间" 
              format="HH:mm"
              value-format="HH:mm"/>
            </el-form-item>
            
          </el-col>
        </el-row>
        <el-row :gutter="20">
          
          <el-col :span="12">
            <el-form-item label="下午开始时间" prop="afternoonStart">
              <el-time-picker v-model="form.afternoonStart" placeholder="请输入下午开始时间" 
              format="HH:mm"
              value-format="HH:mm"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下午结束时间" prop="afternoonEnd">
              <el-time-picker v-model="form.afternoonEnd" placeholder="请输入下午结束时间" 
              format="HH:mm"
              value-format="HH:mm"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          
          <el-col :span="12">
            <el-form-item label="夜间开始时间" prop="nightStart">
              <el-time-picker v-model="form.nightStart" placeholder="请输入夜间开始时间" 
              format="HH:mm"
              value-format="HH:mm"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="夜间结束时间" prop="nightEnd">
              <el-time-picker v-model="form.nightEnd" placeholder="请输入夜间结束时间" 
              format="HH:mm"
              value-format="HH:mm"/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20"> 
          <el-col :span="8">
            <el-form-item label="上午剩余号源" prop="morningRemaining" >
              <el-input v-model="form.morningRemaining" placeholder="上午剩余号源" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下午剩余号源" prop="afternoonRemaining" >
              <el-input v-model="form.afternoonRemaining" placeholder="下午剩余号源" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="夜间剩余号源" prop="nightRemaining" >
              <el-input v-model="form.nightRemaining" placeholder="夜间剩余号源" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="删除标志" prop="deleted">
              <el-input v-model="form.deleted" placeholder="请输入删除标志" />
            </el-form-item>
          </el-col>
        </el-row> -->
        
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
  
  </div>
</template>

<script>
import { listSchedules, getSchedules, delSchedules, addSchedules, updateSchedules } from "@/api/system/hospitals/schedules"
import { listDoctors } from "@/api/system/hospitals/doctors"
import {listDepartments} from "@/api/system/hospitals/departments"
export default {
  name: "Schedules",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      schedulesList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorId: null,
        date: null,
        morningStart: null,
        morningEnd: null,
        afternoonStart: null,
        afternoonEnd: null,
        nightStart: null,
        nightEnd: null,
        morningQuota: null,
        afternoonQuota: null,
        nightQuota: null,
        morningRemaining: null,
        afternoonRemaining: null,
        nightRemaining: null,
        deleted: null,
        doctorName: null,
        deptName: null,
      },
      doctorList: [],
      deptList: [],
      doctorLoading: false,
      deptLoading: false,
      form: {},
      rules: {
        doctorId: [{ required: true, message: "医生ID不能为空", trigger: "blur" }],
        // doctorName:[{required: true,message: "医生姓名必须选择", trigger: "blur" }],
        date: [{ required: true, message: "排班日期不能为空", trigger: "blur" }],
      }
    }
  },
  created() {
    this.getList()
  },
  mounted(){
    this.fetchDoctors();
  },
  methods: {

    async fetchDoctors() {
      try {
        this.doctorLoading = true;
        console.log("Fetching doctors...");
        const response = await listDoctors({});
        console.log("医生数据：", response.rows); // 改进日志输出
        this.doctorList = response.rows
          .filter(item => item.doctorName) // 过滤 doctorName 为 null 的项
          .map(item => ({
            value: item.doctorId,
            label: item.doctorName
          }));
        if (!this.doctorList.length) {
          this.$message.warning('暂无医生数据');
        }
      } catch (error) {
        this.$message.error('获取医生数据失败');
        console.error('Error fetching doctors:', error); // 打印详细错误
      } finally {
        this.doctorLoading = false;
      }
    },

    handleDoctorChange(value) {
      const selectedDoctor = this.doctorList.find(doctor => doctor.value === value);
      this.form.doctorName = selectedDoctor ? selectedDoctor.label : ''; // 可选，更新 doctorName 显示
    },

    getList() {
      this.loading = true
      listSchedules(this.queryParams).then(response => {
        this.schedulesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        scheduleId: null,
        doctorId: null,
        date: null,
        morningStart: null,
        morningEnd: null,
        afternoonStart: null,
        afternoonEnd: null,
        nightStart: null,
        nightEnd: null,
        morningQuota: null,
        afternoonQuota: null,
        nightQuota: null,
        morningRemaining: null,
        afternoonRemaining: null,
        nightRemaining: null,
        createTime: null,
        updateTime: null,
        deleted: null
      }
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scheduleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加医生排班"
    },
    handleUpdate(row) {
      this.reset()
      const scheduleId = row.scheduleId || this.ids
      getSchedules(scheduleId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改医生排班"
      })
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.scheduleId != null) {
            updateSchedules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addSchedules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    handleDelete(row) {
      const scheduleIds = row.scheduleId || this.ids
      this.$modal.confirm('是否确认删除医生排班编号为"' + scheduleIds + '"的数据项？').then(() => {
        return delSchedules(scheduleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleExport() {
      this.download('system/schedules/export', {
        ...this.queryParams
      }, `schedules_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<!-- <style scoped>
.el-card {
  margin: 5px 0;
  padding: 10px;
  border-radius: 5px;
  text-align: center;
}
</style> -->